package com.moleq.mgpos.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.moleq.adapter.FunctionListAdapter;
import com.moleq.adapter.MenuColorAdapter;
import com.moleq.adapter.UserListAdapter;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.models.AgeSetting;
import com.moleq.models.Functions;
import com.moleq.models.GlobalInfo;
import com.moleq.models.MixMatch_detail;
import com.moleq.models.SecuritySetting;
import com.moleq.models.Users;
import com.moleq.mgpos.activities.R;
import com.moleq.service.FunctionService;
import com.moleq.service.ServiceManager;
import com.moleq.service.UsersService;

public class UserSettingActivity extends Activity {
	/** Called when the activity is first created. */

	private Button btn_del, btn_exit, btn_add, btn_undo, btn_save, btn_pwd;
	private PopupWindow window = null;
	private Dialog dialog = null;
	private ListView list, list_per;
	private UserListAdapter listAdapter;
	private MenuColorAdapter colorAdapter;
	private FunctionListAdapter listAdapter_per;
	private List<Users> users = null;
	private List<Functions> functions = null, user_functions = null;
	private UsersService usersservice;
	private FunctionService functionsservice;
	private CheckBox cb_check;
	//private ArrayList<CheckBox> cbs = new ArrayList<CheckBox>();
	private String SaveMode;
	private MessageDialog mMessageDialog;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_setting);
		
		btn_del = (Button) findViewById(R.id.btn_del);
		btn_exit = (Button) findViewById(R.id.btn_close);
		btn_add = (Button) findViewById(R.id.btn_add);
		btn_undo = (Button) findViewById(R.id.btn_undo);
		btn_save = (Button) findViewById(R.id.btn_update);
		btn_pwd = (Button) findViewById(R.id.btn_pwd);
		list = (ListView) findViewById(R.id.lsv_user_list);
		list_per = (ListView) findViewById(R.id.lsv_permissions_list);

		btn_del.setOnClickListener(onClickListener);
		btn_exit.setOnClickListener(onClickListener);
		btn_add.setOnClickListener(onClickListener);
		btn_undo.setOnClickListener(onClickListener);
		btn_save.setOnClickListener(onClickListener);
		btn_pwd.setOnClickListener(onClickListener);

		list.setOnItemClickListener(onItemClickListener);

		usersservice = ServiceManager.getInstance().mUsersService;
		functionsservice = ServiceManager.getInstance().mFunctionService;
		DataBinding();
		SetEnabledTrue();

	}

	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			// TODO Auto-generated method stub
			switch (parent.getId()) {
			case R.id.lv_color_list:
				colorAdapter.ScrollToRow(position);
				break;
			default:
//				listAdapter.ScrollToRow(position);
				RefresItem(position);
				break;
			}
		}

	};

	OnClickListener onClickListener = new OnClickListener() {

		public void onClick(View view) {
			int index;
			int li_user_id;

			switch (view.getId()) {
			case R.id.btn_pwd:
				SaveMode = "";
				if (users.size() <= 0)
					return;
				index = listAdapter.GetSelectedIndex();
				li_user_id = users.get(index).getUs_id();
				if (usersservice.GetUserDetail(li_user_id) != null) {
					popAwindow(view, li_user_id);
				}

				break;
			case R.id.btn_del:
				SaveMode = "Delete";
				if (users.size() <= 1)
					return;
				if (listAdapter.GetSelectedIndex() < 0)
					return;
				ShowMessage("Are you sure to delete this User?",
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);

				break;
			case R.id.btn_close:
				SaveMode = "";
				ShowMessage(
						getResources().getString(R.string.msg_exit_program),
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);
				break;
			case R.id.btn_add:
				SaveMode = "Insert";
				popAwindow(view, -1);
				break;

			case R.id.btn_undo:

				index = listAdapter.GetSelectedIndex();

				RefresItem(index);
				SetEnabledTrue();
				break;
			case R.id.btn_update:

				Save();
				SetEnabledTrue();
				break;
			}
		}
	};

	public void RefresItem(int position) {
		//users = usersservice.getuserlist();
		//listAdapter.notifyDataSetChanged();
		if (users.size() > 0) {
			//listAdapter.setSource(users);
			listAdapter.ScrollToRow(position);
			list.setSelection(position);
			String ls_user_id = String.valueOf(users.get(position).getUs_id());
			if (usersservice.GetUserDetail(users.get(position).getUs_id()) != null) {
				user_functions = functionsservice.getuserfunctionlist(ls_user_id);
				//cbs.clear();
				listAdapter_per.setSource(functions, user_functions);
				listAdapter_per.notifyDataSetChanged();		
				list_per.setAdapter(listAdapter_per);
			}else{
				users = usersservice.getuserlist();
				listAdapter.setSource(users);
				listAdapter.notifyDataSetChanged();
				if(position - 1 >= 0)listAdapter.ScrollToRow(position - 1);
			}
			
		} else {
			list_per.setAdapter(null);
		}
	}

	public void ResetFunction() {

//		CheckBox cb;
////		for (int i = 0; i < cbs.size(); i++) {
//			cb = cbs.get(i);
//			cb.setChecked(false);
//		}

		SetEnabledTrue();
	}

	public void Save() {

		int index = listAdapter.GetSelectedIndex();

		int li_user_id = users.get(index).getUs_id();
//		cbs = listAdapter_per.getCbs();
//		int z = cbs.size();
		for (int i = 0; i < functions.size(); i++) {

			boolean check = functions.get(i).getIscheck();
			int sfun = functions.size();
			int li_fs_id = functions.get(i).getFs_id();

			if (functionsservice.SelectFunction(li_user_id, li_fs_id)) {

				if (check == false) {
					if (GlobalInfo.getInstance().isMGNetwork) {
						//Group itemSettingx = mGroupSettingService.Find();
						SecuritySetting mSecuritySetting = functionsservice.FindSecurity(li_user_id,li_fs_id);
						mMGCreateFiles.createrFile(mSecuritySetting.toMGData("DELETE","S"));//UPDATE,DELETE
					}
					functionsservice.DeleteFunction(li_user_id, li_fs_id);
					
				}
			} else {
				if (check == true) {
					functionsservice.InsertFunction(li_user_id, li_fs_id);
					
					if (GlobalInfo.getInstance().isMGNetwork) {
						//Group itemSettingx = mGroupSettingService.Find();
						SecuritySetting mSecuritySetting = functionsservice.FindSecurity(li_user_id,li_fs_id);
						mMGCreateFiles.createrFile(mSecuritySetting.toMGData("INSERT"));//UPDATE,DELETE
					}
				}
			}

		}

	}

	Button btn_menu_color;

	private void popAwindow(View parent, int userid) {
		boolean lb_active = false;
		Drawable drawable = null;
		if (dialog == null) {
			dialog = new Dialog(this, R.style.dialog2);
			dialog.setContentView(R.layout.dialog_detail);
		}
		dialog.show();
		Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
		Button bt_ok = (Button) dialog.findViewById(R.id.btn_ok);

		btn_cancel.setOnClickListener(onClickPopupWindowListener);
		bt_ok.setOnClickListener(onClickPopupWindowListener);

		EditText et_name = (EditText) dialog.findViewById(R.id.et_user_name);
		EditText et_pwd = (EditText) dialog.findViewById(R.id.et_user_pwd);
		EditText et_pwd_cfg = (EditText) dialog
				.findViewById(R.id.et_user_pwd_cfg);
		EditText et_id = (EditText) dialog.findViewById(R.id.et_user_id);
		CheckBox et_active = (CheckBox) dialog.findViewById(R.id.cb_active);
		CheckBox cb_manager = (CheckBox) dialog.findViewById(R.id.cb_manager);
		EditText et_login_id = (EditText) dialog.findViewById(R.id.et_login_id);
		btn_menu_color = (Button) dialog.findViewById(R.id.btn_menu_color);
		btn_menu_color.setOnClickListener(onClickPopupWindowListener);

		if (userid > 0) {
			Users user = usersservice.GetUserDetail(userid);
			if (user != null) {
				et_login_id.clearFocus();
				et_login_id.setEnabled(false);
				et_name.setFocusable(true);
				et_name.requestFocus();
				et_name.setFocusableInTouchMode(true);
				et_name.setText(user.getUs_info());
				et_pwd.setText(user.getUs_pwd());
				et_pwd_cfg.setText(user.getUs_pwd());
				et_id.setText(String.valueOf(user.getUs_id()));
				et_login_id.setText(user.getUs_login_id());

				if (user.getUs_color() == 1) {
					drawable = this.getResources().getDrawable(
							R.drawable.button_1);
				} else if (user.getUs_color() == 2) {
					drawable = this.getResources().getDrawable(
							R.drawable.button_2);
				} else if (user.getUs_color() == 3) {
					drawable = this.getResources().getDrawable(
							R.drawable.button_3);
				} else if (user.getUs_color() == 4) {
					drawable = this.getResources().getDrawable(
							R.drawable.button_4);
				} else if (user.getUs_color() == 5) {
					drawable = this.getResources().getDrawable(
							R.drawable.button_5);
				} else {
					drawable = this.getResources().getDrawable(
							R.drawable.button_1);
				}
				btn_menu_color.setBackgroundDrawable(drawable);
				btn_menu_color.setTag(user.getUs_color());
				if (user.getUs_active().equals("Y")) {
					lb_active = true;
				} else {
					lb_active = false;
				}
				et_active.setChecked(lb_active);
				if (user.getUs_manager().equals("Y")) {
					cb_manager.setChecked(true);
				} else {
					cb_manager.setChecked(false);
				}
			}

		} else {
			et_login_id.setFocusable(true);
			et_login_id.requestFocus();
			et_login_id.setFocusableInTouchMode(true);
			et_login_id.setEnabled(true);

			et_name.setText("");
			et_pwd.setText("");
			et_pwd_cfg.setText("");
			et_id.setText("");
			et_login_id.setText("");
			et_active.setChecked(true);
			cb_manager.setChecked(false);
			drawable = this.getResources().getDrawable(R.drawable.button_1);
			btn_menu_color.setBackgroundDrawable(drawable);
			btn_menu_color.setTag(1);
		}
	}

	Dialog colorDialog = null;

	private void ColorWindow() {
		if (colorDialog == null) {
			colorDialog = new Dialog(this, R.style.dialog2);
			colorDialog.setContentView(R.layout.dialog_perview_color_item);
		}

		ListView lv_color_list = (ListView) colorDialog
				.findViewById(R.id.lv_color_list);
		Button btn_color_ok = (Button) colorDialog
				.findViewById(R.id.btn_color_ok);
		Button btn_color_cancel = (Button) colorDialog
				.findViewById(R.id.btn_color_cancel);
		if (colorAdapter == null) {
			colorAdapter = new MenuColorAdapter(this);
			lv_color_list.setAdapter(colorAdapter);
		}
		int position = (Integer) btn_menu_color.getTag() - 1;
		colorAdapter.ScrollToRow(position);
		lv_color_list.setOnItemClickListener(onItemClickListener);
		btn_color_ok.setOnClickListener(onClickPopupWindowListener);
		btn_color_cancel.setOnClickListener(onClickPopupWindowListener);
		colorDialog.show();
	}

	OnClickListener onClickPopupWindowListener = new OnClickListener() {
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.btn_cancel:
				dialog.dismiss();
				break;
			case R.id.btn_ok:
				String ls_user_name,
				ls_user_pwd,
				ls_user_pwd_cfg,
				ls_user_id,
				ls_login_id;
				int colorId;
				boolean lb_user_active,
				lb_user_manager;

				EditText et_name = (EditText) dialog
						.findViewById(R.id.et_user_name);
				EditText et_pwd = (EditText) dialog
						.findViewById(R.id.et_user_pwd);
				EditText et_pwd_cfg = (EditText) dialog
						.findViewById(R.id.et_user_pwd_cfg);
				EditText et_id = (EditText) dialog
						.findViewById(R.id.et_user_id);
				CheckBox et_active = (CheckBox) dialog
						.findViewById(R.id.cb_active);
				CheckBox cb_manager = (CheckBox) dialog
						.findViewById(R.id.cb_manager);
				EditText et_login_id = (EditText) dialog
						.findViewById(R.id.et_login_id);

				ls_user_name = et_name.getText().toString();
				ls_login_id = et_login_id.getText().toString();
				ls_user_pwd = et_pwd.getText().toString();
				ls_user_pwd_cfg = et_pwd_cfg.getText().toString();
				ls_user_id = et_id.getText().toString();
				lb_user_active = et_active.isChecked();
				lb_user_manager = cb_manager.isChecked();
				colorId = (Integer) btn_menu_color.getTag();

				Users u = new Users();
				if (lb_user_active == true) {
					u.setUs_active("Y");
				} else {
					u.setUs_active("N");
				}
				if (lb_user_manager) {
					u.setUs_manager("Y");
				} else {
					u.setUs_manager("N");
				}
				u.setUs_confirm_pwd(ls_user_pwd_cfg);

				u.setUs_info(ls_user_name);
				u.setUs_login_id(ls_login_id);
				u.setUs_pwd(ls_user_pwd);
				u.setUs_color(colorId);

				if (validation(dialog) == true) {
					boolean bo;
					if (SaveMode.equals("Insert")) {
						
						bo = usersservice.InsertUser(u);
						
						if (GlobalInfo.getInstance().isMGNetwork) {
							Users user = usersservice.GetUserDetail(usersservice.FindUserId(ls_login_id)) ;
							mMGCreateFiles.createrFile(user.toMGData("INSERT"));//UPDATE,DELETE
							}
						
					} else {
						u.setUs_id(Integer.valueOf(ls_user_id));
						
						bo = usersservice.UpdateUser(u);
						
						if (GlobalInfo.getInstance().isMGNetwork) {
//							ItemSetting itemSettingx = mItemSettingService.findByUpc(upc);
							Users user = usersservice.GetUserDetail(usersservice.FindUserId(ls_login_id)) ;
							mMGCreateFiles.createrFile(user.toMGData("UPDATE"));//UPDATE,DELETE
							}
					}
					UpdateMessage(bo);
					listAdapter.setSource(users);
					listAdapter.notifyDataSetChanged();
					
					if (SaveMode.equals("Insert")) {
						listAdapter.ScrollToRow(users.size() - 1);
						RefresItem(users.size() - 1);
					}else{
						RefresItem(listAdapter.GetSelectedIndex());
					}

				}

				break;
			case R.id.btn_menu_color:
				ColorWindow();
				break;
			case R.id.btn_color_ok:
				colorDialog.dismiss();
				btn_menu_color.setBackgroundDrawable(colorAdapter
						.getColorDrawable());
				btn_menu_color.setTag(colorAdapter.GetSelectedIndex() + 1);
				break;
			case R.id.btn_color_cancel:
				colorDialog.dismiss();
				break;
			}
		}
	};

	public boolean validation(Dialog dialog) {

		String ls_user_name, ls_user_pwd, ls_user_pwd_cfg, ls_user_id, ls_login_id;
		boolean lb_user_active;

		EditText et_name = (EditText) dialog.findViewById(R.id.et_user_name);
		EditText et_pwd = (EditText) dialog.findViewById(R.id.et_user_pwd);
		EditText et_pwd_cfg = (EditText) dialog
				.findViewById(R.id.et_user_pwd_cfg);
		EditText et_id = (EditText) dialog.findViewById(R.id.et_user_id);
		CheckBox et_active = (CheckBox) dialog.findViewById(R.id.cb_active);
		EditText et_login_id = (EditText) dialog.findViewById(R.id.et_login_id);

		ls_user_name = et_name.getText().toString();
		ls_login_id = et_login_id.getText().toString();
		ls_user_pwd = et_pwd.getText().toString();
		ls_user_pwd_cfg = et_pwd_cfg.getText().toString();
		ls_user_id = et_id.getText().toString();
		lb_user_active = et_active.isChecked();

		if (ls_login_id == null || ls_login_id == ""
				|| ls_login_id.trim().length() <= 0) {
			ShowMessage("The User Login Id no can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return false;
		}

		if (ls_user_name == null || ls_user_name == ""
				|| ls_user_name.trim().length() <= 0) {
			ShowMessage("The User Name no can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return false;
		}

		if (ls_user_pwd == null || ls_user_pwd == ""
				|| ls_user_pwd.trim().length() <= 0) {
			ShowMessage("The Password no can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return false;
		}

		if (!ls_user_pwd_cfg.equals(ls_user_pwd)) {
			ShowMessage("Passwords do not match.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return false;
		}

		if (SaveMode.equals("Insert")) {
			if (usersservice.CheckUsers(Integer.valueOf(ls_login_id))) {
				ShowMessage("The User Login Id was already exist.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return false;
			}
		}

		return true;
	}

	public void DataBinding() {

		users = usersservice.getuserlist();
		if (users.size() <= 0) {
			return;
		}
		list = (ListView) findViewById(R.id.lsv_user_list);

		if (listAdapter == null)
			listAdapter = new UserListAdapter(this, users);

		list.setAdapter(listAdapter);

		int index = Integer.valueOf(listAdapter.GetSelectedIndex());

		String ls_user_id = String.valueOf(users.get(0).getUs_id());

		functions = functionsservice.getfunctionlist();
		user_functions = functionsservice.getuserfunctionlist(ls_user_id);
		if (listAdapter_per == null){
			listAdapter_per = new FunctionListAdapter(this, functions,
					user_functions);
			
		}
		list_per.setAdapter(listAdapter_per);
	}

	public void SetEnabledFalse() {
		btn_add.setEnabled(false);
		btn_del.setEnabled(false);
		btn_exit.setEnabled(false);
		list.setEnabled(false);
		btn_undo.setEnabled(true);
		btn_save.setEnabled(true);
		btn_pwd.setEnabled(false);

	}

	public void SetEnabledTrue() {
		btn_add.setEnabled(true);
		btn_del.setEnabled(true);
		btn_exit.setEnabled(true);
		list.setEnabled(true);
		btn_undo.setEnabled(false);
		btn_save.setEnabled(false);
		btn_pwd.setEnabled(true);
	}

	public void UpdateMessage(boolean bo) {

		if (bo) {
			Toast.makeText(UserSettingActivity.this, "Save completed.",
					Toast.LENGTH_SHORT).show();
			DataBinding();
			dialog.dismiss();
		} else {
			ShowMessage("Save Error.", MessageDialog.MESSAGE_BOX_OK,
					MessageDialog.ICON_INFO);
		}
		// switch (bo) {
		// case 0:
		//
		// break;
		// case 1:
		// // ShowMessage("Save completed.", MessageDialog.MESSAGE_BOX_OK,
		// // MessageDialog.ICON_INFO);
		//
		//
		// }

	}

	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		public void onClickYes() {
			// TODO Auto-generated method stub
			if (SaveMode.endsWith("Delete")) {
				String dep_no = "";
				int index = listAdapter.GetSelectedIndex();
				int li_user_id = users.get(index).getUs_id();

				int index2 = -1;
				if (index == 0 && users.size() > 1) {
					index2 = index;
					dep_no = String.valueOf(users.get(index).getUs_id());
				} else if (index > 0) {
					index2 = index - 1;
					dep_no = String.valueOf(users.get(index2).getUs_id());
				}
				
				if (GlobalInfo.getInstance().isMGNetwork) {
					Users user = usersservice.GetUserDetail(li_user_id);
					mMGCreateFiles.createrFile(user.toMGData("DELETE"));//UPDATE,DELETE
				}
				if (usersservice.DeleteUser(li_user_id)) {
					
					if (GlobalInfo.getInstance().isMGNetwork) {
						List<SecuritySetting> ss = functionsservice.getSecuritySettingById(li_user_id);
						if(ss.size() > 0 )mMGCreateFiles.createrFile(ss.get(0).toMGData("DELETE","A"));//UPDATE,DELETE
					}
					functionsservice.DeleteFunctionbyid(li_user_id);
				}

				users = usersservice.getuserlist();
				if (listAdapter == null)
					listAdapter = new UserListAdapter(UserSettingActivity.this,
							users);

				listAdapter.setSource(users);
				listAdapter.notifyDataSetChanged();
				list.setAdapter(listAdapter);
				listAdapter.ScrollToRow(index2);
				RefresItem(index2);

				mMessageDialog.dismiss();
			} else {

				finish();
			}

		}

		public void onClickNo() {
			// TODO Auto-generated method stub
			mMessageDialog.dismiss();
		}

		public void onClickOK() {
			// TODO Auto-generated method stub
			mMessageDialog.dismiss();
		}

	};

	public void ShowMessage(String ls_msg, int style, int icon) {
		mMessageDialog = new MessageDialog(UserSettingActivity.this);
		mMessageDialog.setStyle(style);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(ls_msg);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}

}